﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using System.Data;
using ElingOA6_Admin_DSJCJ.Areas.Admin.Models;
using Newtonsoft.Json;
using FredCK.FCKeditorV2;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using Newtonsoft.Json.Linq;
using SignalR;
using System.Net;
using ElingOA6_Admin_DSJCJ.Scripts.SWFUpload.App_Code;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 信息发布
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class DocumentPubController : AdminBaseController
    {
        //
        // GET: /Admin/DocumentPub/

        /// <summary>
        /// 信息类别逻辑类
        /// </summary>
        private BLL.DocCls docClsBLL = new BLL.DocCls();
        /// <summary>
        /// 系统参数逻辑类
        /// </summary>
        private BLL.SysParam sysParamBLL = new BLL.SysParam();
        /// <summary>
        /// 通用方法逻辑类
        /// </summary>
        private BLL.Common commonBLL = new BLL.Common();
        /// <summary>
        /// 信息逻辑类
        /// </summary>
        private BLL.Document documentBLL = new BLL.Document();
        /// <summary>
        /// 模板逻辑类
        /// </summary>
        private BLL.SysTemplate sysTemplateBLL = new BLL.SysTemplate();
        /// <summary>
        /// 权限逻辑类
        /// </summary>
        private BLL.DocClsAuthority docClsAuthorityBLL = new BLL.DocClsAuthority();
        /// <summary>
        /// 员工逻辑类
        /// </summary>
        private BLL.HREmpl hrEmplBLL = new BLL.HREmpl();
        /// <summary>
        /// 员工岗位逻辑类
        /// </summary>
        private BLL.HREmplPosition hrEmplPositionBLL = new BLL.HREmplPosition();
        /// <summary>
        /// 工作组人员逻辑类
        /// </summary>
        private BLL.HRWorkGrpMember hrWorkGrpMemberBLL = new BLL.HRWorkGrpMember();
        /// <summary>
        /// 附件逻辑类
        /// </summary>
        private BLL.DocAttach docAttachBLL = new BLL.DocAttach();
        /// <summary>
        /// 部门逻辑类
        /// </summary>
        private BLL.HRDept hrDeptBLL = new BLL.HRDept();
        /// <summary>
        /// 信息文档合发单位逻辑类
        /// </summary>
        private BLL.DocumentUnionPubEmpl documentUnionPubEmplBLL = new BLL.DocumentUnionPubEmpl();
        /// <summary>
        /// 通知对象BLL
        /// </summary>
        private BLL.DocRecObject docRecObjectBLL = new BLL.DocRecObject();
        /// <summary>
        /// 信息文档呈送BLL
        /// </summary>
        private BLL.DocReference docReferenceBLL = new BLL.DocReference();
        /// <summary>
        /// 信息文档查看权限逻辑类
        /// </summary>
        private BLL.documentAuthority documentAuthorityBLL = new BLL.documentAuthority();
        /// <summary>
        /// 信息发布
        /// </summary>
        [AuthorityActionFilter("m_DocumentPub", Order = 1)]
        [LogPageActionFilter("信息发布", Order = 2)]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 文档列表
        /// </summary>
        /// <returns></returns>
        public ActionResult DocumentList(string docClsCd = "", int id = 1)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            ActionResult actionResult = null;
            string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            Model.DocCls docClsModel = new Model.DocCls();
            string tableName = "";
            ViewData["isAuthority"] = false;
            ViewData["isInportEaccount"] = false;
            if (docClsCd == "")
            {
                tableName = "dbo.fn_GetDocumentALLByCTE('" + entityNo + "','" + deptNo + "','" + empNo + "','PUB')";
            }
            else
            {
                docClsCd = Fetch.InspectData(docClsCd, CheckGetEnum.Safety);
                if (docClsCd != "")
                {
                    docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                    if (docClsModel != null)
                    {
                        tableName = "dbo.fn_GetDocumentByCTE('" + docClsCd + "','" + entityNo + "','" + deptNo + "','" + empNo + "','PUB')";
                        if (docClsModel.FDocClsProp != BaseStruct.DocClsTypeStruct.EMPTY)
                        {
                            ViewData["isAuthority"] = docClsBLL.ExistsAuthorityDocClsNo(entityNo, empNo, deptNo, "PUB", docClsCd);
                        }
                    }
                }
            }
            if (docClsModel.FDocClsProp == BaseStruct.DocClsTypeStruct.SINGLE)
            {
                //单信息
                decimal docId = documentBLL.GetDocIdDocClsCd(entityNo, docClsCd);
                if (docId > 0)
                {
                    actionResult = DocumentPubEdit(docId, docClsCd, Common.BaseStruct.ActionOperationStruct.EDIT);
                }
                else
                {
                    actionResult = DocumentPubEdit(0, docClsCd, Common.BaseStruct.ActionOperationStruct.ADD_SAME);
                }
            }
            else
            {
                //多信息
                //判断是否可以引入文明台账文件
                if (sysParamBLL.GetParamValue("OA_IMPORT_ACCFILE", entityNo) == "Y")
                {
                    ViewData["isInportEaccount"] = true;
                }
                int pageRowSize = 15;
                int pageIndex = id;
                ViewData["pageIndex"] = id - 1;

                string fiedls = "*";
                int total;
                //初始化查询条件
                Models.DocQueryConditionModel conditionModel = new DocQueryConditionModel();
                string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                string queryWhere = " FEmplNo='" + emplNo + "' AND FRecycle='N'";
                ViewData["docQueryCondition"] = JsonConvert.SerializeObject(conditionModel);
                queryWhere += " AND FIsReference='N'";
                DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageRowSize, pageIndex, queryWhere, "FIsTop desc,FTopSeq asc,FPubDate", 1, out total);
                List<DocumentGridModel> documentAllList = new List<DocumentGridModel>();
                List<DocumentGridModel> documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

                for (int i = 0; i < total; i++)
                {
                    documentAllList.Add(null);
                }
                for (int i = 0; i < pageRowSize; i++)
                {
                    if (documentList.Count > i)
                    {
                        documentAllList[((pageIndex - 1) * pageRowSize) + i] = documentList[i];
                    }
                }
                if (docClsCd == "")
                {
                    ViewData["docClsPathName"] = "全部类别";
                }
                else
                {
                    ViewData["docClsPathName"] = docClsBLL.GetDocClsPathNames(entityNo, docClsCd);
                }
                DocumentListViewModel documentListVewModel = new DocumentListViewModel(docClsModel, documentAllList);



                actionResult = View("DocumentList", documentListVewModel);
            }
            return actionResult;
        }

        /// <summary>
        /// 文档列表翻页操作
        /// </summary>
        /// <returns>视图</returns>
        public ActionResult DocumentListPartial()
        {
            int pageIndex = Request.Params["pageIndex"] == null ? 0 : int.Parse(Request.Params["pageIndex"].ToString());
            int pageCount = Request.Params["PageCount"] == null ? 0 : int.Parse(Request.Params["PageCount"].ToString());
            int pageRowSize = Request.Params["pageRowSize"] == null ? 0 : int.Parse(Request.Params["pageRowSize"].ToString());
            int pageRowCount = Request.Params["pageRowCount"] == null ? 0 : int.Parse(Request.Params["pageRowCount"].ToString());

            string docClsCd = Request.Params["docClsCd"];
            string callbackArg = DevExpressHelper.CallbackArgument;
            string command = Request.Params["command"] == null ? "" : Request.Params["command"].ToString();

            if (command == "PAGERONCLICK")
            {
                string[] args = callbackArg.Split(new char[1] { '|' });
                string arg = args[args.Count() - 1];

                switch (arg)
                {
                    case "PBN;":
                        {
                            //下一页
                            pageIndex = pageIndex + 2;
                            break;
                        }
                    case "PBP;":
                        {
                            //上一页
                            //pageIndex = pageIndex;
                            break;
                        }
                    case "PBL;":
                        {
                            //最后一页
                            pageIndex = pageCount;
                            break;
                        }
                    case "PBF;":
                        {
                            //第一页
                            pageIndex = 1;
                            break;
                        }
                    default:
                        {
                            //点击数字页码
                            string tempIndex = arg.Replace("PN", "");
                            tempIndex = tempIndex.Replace(";", "");
                            if (RegExp.IsNumeric(tempIndex))
                            {
                                pageIndex = int.Parse(tempIndex) + 1;
                            }
                            break;
                        }

                }
            }
            else
            {
                if (command == "REFRESH")
                {
                    //第一页
                    pageIndex = 1;
                }
                else
                {
                    pageIndex = pageIndex + 1;
                }
            }

            string entityNo = GlobalConstant.ENTITYNO;
            string deptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);

            ViewData["pageIndex"] = pageIndex - 1;

            string fiedls = "*";
            int total;
            Model.DocCls docClsModel = new Model.DocCls();
            string tableName = "";
            if (docClsCd == "")
            {
                tableName = "dbo.fn_GetDocumentALLByCTE('" + entityNo + "','" + deptNo + "','" + empNo + "','PUB')";
            }
            else
            {
                docClsCd = Fetch.InspectData(docClsCd, CheckGetEnum.Safety);
                if (docClsCd != "")
                {
                    docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
                    if (docClsModel != null)
                    {
                        tableName = "dbo.fn_GetDocumentByCTE('" + docClsCd + "','" + entityNo + "','" + deptNo + "','" + empNo + "','PUB')";
                    }
                }
            }
            ViewData["isAuthority"] = false;
            ViewData["isInportEaccount"] = false;

            //查询条件
            string conditionString = Request.Params["queryCondition"].ToString();

            string queryWhere = " FEmplNo='" + empNo + "' AND FRecycle='N'";
            if (conditionString != "")
            {
                Models.DocQueryConditionModel conditionModel = JsonConvert.DeserializeObject<Models.DocQueryConditionModel>(conditionString);
                if (!string.IsNullOrEmpty(conditionModel.FStatus))
                {
                    queryWhere += " AND FStatus='" + Fetch.InspectData(conditionModel.FStatus, CheckGetEnum.Safety) + "'";
                }
                if (!string.IsNullOrEmpty(conditionModel.FIsEnroll))
                {
                    queryWhere += " AND FIsEnroll='" + Fetch.InspectData(conditionModel.FIsEnroll, CheckGetEnum.Safety) + "'";
                }
                if (!string.IsNullOrEmpty(conditionModel.FTitle))
                {
                    if (conditionModel.FTitle.Trim() != "")
                    {
                        queryWhere += " AND FTitle Like '%" + Fetch.InspectData(conditionModel.FTitle, CheckGetEnum.Safety) + "%'";
                    }
                }
                if (conditionModel.BeginPubDate.HasValue && conditionModel.EndPubDate.HasValue)
                {
                    queryWhere += " AND DATEDIFF(day,'" + conditionModel.BeginPubDate.Value + "',FPubDate)>=0 AND DATEDIFF(day,'" + conditionModel.EndPubDate.Value + "',FPubDate)<=0 ";
                }
                else
                {
                    if (conditionModel.BeginPubDate.HasValue)
                    {
                        queryWhere += " AND DATEDIFF(day,'" + conditionModel.BeginPubDate.Value + "',FPubDate)>=0";
                    }
                    else
                    {
                        if (conditionModel.EndPubDate.HasValue)
                        {
                            queryWhere += " AND  DATEDIFF(day,'" + conditionModel.EndPubDate.Value + "',FPubDate)<=0 ";

                        }
                    }
                }
                if (conditionModel.PubEmplList != null && conditionModel.PubEmplList.Count > 0)
                {
                    // 目前支持单用户选择
                    string emplNo = conditionModel.PubEmplList[0].Value;
                    queryWhere += " AND FEmplNo='" + emplNo + "'";
                }
                if (conditionModel.DeptList != null && conditionModel.DeptList.Count > 0)
                {
                    // 目前支持单部门选择
                    string queryDeptNo = conditionModel.DeptList[0].Value;
                    queryWhere += " AND FDeptNo='" + queryDeptNo + "'";
                }
                if (conditionModel.WorkGroupList != null && conditionModel.WorkGroupList.Count > 0)
                {
                    // 目前支持单部门选择
                    string workGrpNo = conditionModel.WorkGroupList[0].Value;
                    queryWhere += " AND FWorkGrpNo='" + workGrpNo + "'";
                }
            }
            queryWhere += " AND FIsReference='N'";
            DataSet ds = commonBLL.GetListByPage(tableName, fiedls, pageRowSize, pageIndex, queryWhere, "FIsTop desc,FTopSeq asc,FPubDate", 1, out total);
            List<DocumentGridModel> documentAllList = new List<DocumentGridModel>();
            List<DocumentGridModel> documentList = ViewDataRowToModel.DataTableToListDocuemt(ds.Tables[0]);

            for (int i = 0; i < total; i++)
            {
                documentAllList.Add(null);
            }
            for (int i = 0; i < pageRowSize; i++)
            {
                if (documentList.Count > i)
                {
                    documentAllList[((pageIndex - 1) * pageRowSize) + i] = documentList[i];
                }
            }
            DocumentListViewModel documentListVewModel = new DocumentListViewModel(docClsModel, documentAllList);
            bool isAuthority = docClsBLL.ExistsAuthorityDocClsNo(entityNo, empNo, deptNo, "PUB", docClsCd);
            ViewData["isAuthority"] = isAuthority;
            if (docClsCd == "")
            {
                ViewData["docClsPathName"] = "全部类别";
            }
            else
            {
                ViewData["docClsPathName"] = docClsBLL.GetDocClsPathNames(entityNo, docClsCd);
            }
            return PartialView("DocumentListPartial", documentListVewModel);
        }

        /// <summary>
        /// 信息发布编辑(增加)
        /// </summary>
        /// <param name="docId">文档编号</param>
        /// <param name="docClsCd">栏目编号</param>
        /// <param name="actionOperation">操作类型</param>
        /// <returns>视图</returns>
        public ActionResult DocumentPubEdit(decimal docId, string docClsCd, string actionOP, int pageIndex = 1)
        {
            ViewData["pageIndex"] = pageIndex;
            ViewData["gridDocClsCd"] = docClsCd;//表格传递的栏目编号
            //判断是否已经审核
            if (actionOP == BaseStruct.ActionOperationStruct.EDIT)
            {
                Model.Document docModel = documentBLL.GetModel(docId);
                if (docClsCd == "")
                {
                    docClsCd = docModel.FDocClsCd;
                }
                Model.DocCls docClsModel = docClsBLL.GetModel(GlobalConstant.ENTITYNO, docClsCd);
                if (docModel != null && docClsModel != null)
                {
                    if (docModel.FStatus == "Y" && docClsModel.FIsNeedAudit == "Y" && docModel.FIsEnroll != "U")
                    {
                        return RedirectToAction("DocumentLook", "DocumentPub", new { docId = docId, docClsCd = docClsCd, docType = "PUB" });
                    }
                    else
                    {
                        DocumentPubEdit(docId, docClsCd, actionOP, "", null, "PUB");
                    }
                }
                else
                {
                    //跳转到错误页面
                    return View("Error");
                }
            }
            else
            {
                DocumentPubEdit(docId, docClsCd, actionOP, "", null, "PUB");
            }
            return View("DocumentPubEdit");
        }
        /// <summary>
        /// 信息维护
        /// </summary>
        /// <param name="docId">文档编号</param>
        /// <param name="docClsCd">栏目编号</param>
        /// <param name="actionOperation">操作类型</param>
        /// <returns>视图</returns>
        public ActionResult DocumentManageEdit(decimal docId, string docClsCd, string actionOP, int pageIndex = 1)
        {
            ViewData["pageIndex"] = pageIndex;
            ViewData["gridDocClsCd"] = docClsCd;//表格传递的栏目编号
            //判断是否已经审核
            if (actionOP == BaseStruct.ActionOperationStruct.EDIT)
            {
                Model.Document docModel = documentBLL.GetModel(docId);
                if (docModel != null)
                {
                    Model.DocCls docClsModel = docClsBLL.GetModel(GlobalConstant.ENTITYNO, docModel.FDocClsCd);
                    if (docClsModel != null)
                    {
                        if (docModel.FStatus == "Y" && docClsModel.FIsNeedAudit == "Y" && docModel.FIsEnroll != "U")
                        {
                            return RedirectToAction("DocumentLook", "DocumentPub", new { docId = docId, docClsCd = docClsCd, docType = "MANAGE", pageIndex = pageIndex });
                        }
                        else
                        {
                            DocumentPubEdit(docId, docClsCd, BaseStruct.ActionOperationStruct.EDIT, "", null, "MANAGE");
                        }
                    }
                }
            }
            else
            {
                DocumentPubEdit(docId, docClsCd, BaseStruct.ActionOperationStruct.EDIT, "", null, "MANAGE");
            }
            return View("DocumentPubEdit");
        }
        /// <summary>
        /// 信息审核
        /// </summary>
        /// <param name="docId">文档编号</param>
        /// <param name="docClsCd">栏目编号</param>
        /// <param name="actionOperation">操作类型</param>
        /// <returns>视图</returns>
        public ActionResult DocumentAuditEdit(decimal docId, string docClsCd, string actionOP, int pageIndex = 1)
        {
            ViewData["pageIndex"] = pageIndex;
            ViewData["gridDocClsCd"] = docClsCd;//表格传递的栏目编号
            DocumentPubEdit(docId, docClsCd, BaseStruct.ActionOperationStruct.EDIT, "", null, "AUDIT");
            return View("DocumentPubEdit");
        }
        /// <summary>
        /// 信息查看
        /// </summary>
        /// <param name="docId"></param>
        /// <param name="docClsCd"></param>
        /// <returns></returns>
        public ActionResult DocumentLook(decimal docId, string docClsCd, string docType, int pageIndex = 1)
        {
            ViewData["pageIndex"] = pageIndex;
            ViewData["gridDocClsCd"] = docClsCd;//表格传递的栏目编号
            DocumentPubEdit(docId, docClsCd, BaseStruct.ActionOperationStruct.EDIT, "", null, docType);
            return View("DocumentLook");
        }

        /// <summary>
        /// 信息类别编辑(增加)
        /// </summary>
        /// <param name="docClsCd">栏目编号</param>
        /// <param name="actionOP">操作类型</param>
        /// <param name="jsAlert">错误信息</param>
        /// <param name="docClsModel">信息类别实体类</param>
        /// <param name="docClsModel">文档类型 PUB-发布 MANAGE-维护 AUDIT-审核</param>
        /// <returns>
        /// 视图
        /// </returns>
        private ActionResult DocumentPubEdit(decimal docId, string docClsCd, string actionOP, string jsAlert, Model.Document documentModel, string docType)
        {
            //获取当前数据库时间
            ViewData["serverTime"] = commonBLL.GetServerDateTime();
            string docClsPath = docClsBLL.GetDocClsCdS(docClsCd, GlobalConstant.ENTITYNO);//获取当前类别和其父类别组成的路径
            Session["FCKeditor:UserFilesPath"] = GenerateUtil.GetConfigValue("FCKeditor:UserFilesPath") + docClsPath + "/";

            //级别
            List<SelectListItem> itemsJB = new List<SelectListItem>();
            itemsJB.Add(new SelectListItem() { Text = "正级", Value = BaseStruct.ClsAuthorityPropStruct.ZHENGJI });
            itemsJB.Add(new SelectListItem() { Text = "副级", Value = BaseStruct.ClsAuthorityPropStruct.FUJI });
            itemsJB.Add(new SelectListItem() { Text = "正副级", Value = BaseStruct.ClsAuthorityPropStruct.ZHENGFUJI });
            itemsJB.Add(new SelectListItem() { Text = "任何人", Value = BaseStruct.ClsAuthorityPropStruct.RENHEREN });
            ViewData["clsAuthorityPropSelection"] = itemsJB;

            if (documentModel == null)
            {
                switch (actionOP)
                {
                    case BaseStruct.ActionOperationStruct.ADD_SAME:
                        {
                            documentModel = new Model.Document();
                            break;
                        }
                    case BaseStruct.ActionOperationStruct.EDIT:
                        {
                            documentModel = documentBLL.GetModel(docId);
                            docClsCd = documentModel.FDocClsCd;
                            break;
                        }
                }
            }
            string entityNo = GlobalConstant.ENTITYNO;
            string emplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, docClsCd);
            if (docClsModel != null)
            {
                ViewData["ProductCaption"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTCAPTION);
                ViewData["ProductKey"] = OperateSession.get(GlobalConstant.PARAM_PRODUCTKEY);
                //编辑模式
                List<SelectListItem> items = new List<SelectListItem>();
                if (docClsModel.FEditMode == "A")
                {
                    items.Add(new SelectListItem() { Text = "HTML", Value = "0" });
                    items.Add(new SelectListItem() { Text = "WORD", Value = "1" });
                    items.Add(new SelectListItem() { Text = "EXCEL", Value = "2" });
                    items.Add(new SelectListItem() { Text = "PowerPoint", Value = "3" });
                }
                else
                {
                    if (docClsModel.FEditMode == "H")
                    {
                        items.Add(new SelectListItem() { Text = "HTML", Value = "0" });
                    }
                    else
                    {
                        items.Add(new SelectListItem() { Text = "WORD", Value = "1" });
                        items.Add(new SelectListItem() { Text = "EXCEL", Value = "2" });
                        items.Add(new SelectListItem() { Text = "PowerPoint", Value = "3" });
                    }
                }
                if (docClsModel.FDefaultEditMode == "H")
                {
                    ViewData["defaultEditMode"] = "0";
                }
                else
                {
                    ViewData["defaultEditMode"] = "1";
                }
                ViewData["editModeSelection"] = items;

                if (docType == "PUB")
                {
                    ViewData["isTop"] = "N";
                }
                else
                {
                    ViewData["isTop"] = "Y";
                }

                //缩略图
                items = new List<SelectListItem>();
                items.Add(new SelectListItem() { Text = "按比例自动适应", Value = "1" });
                items.Add(new SelectListItem() { Text = "按尺寸自动适应", Value = "2" });
                items.Add(new SelectListItem() { Text = "手工编辑后上传", Value = "3" });
                ViewData["thumbGenTypeSelection"] = items;

                //绑定模板默认值
                ViewData["templateDefaultVlaue"] = "-1";
                List<Model.SysTemplate> sysTemplateList = sysTemplateBLL.GetListByTemplateType(entityNo, docClsCd, docClsModel.FDefaultEditMode);
                ViewData["attachJsonString"] = "";

                //文档查看权限
                if (docClsModel.FIsCtrlLookAuthority == "Y")
                {
                    if (docClsModel.FLookAuthorityMode == "D")
                    {
                        ViewData["showLookTab"] = "Y";
                    }
                    else
                    {
                        ViewData["showLookTab"] = "N";
                    }
                }
                else
                {
                    ViewData["showLookTab"] = "N";
                }
                List<Model.documentAuthority> documentAuthorityList = new List<Model.documentAuthority>();

                if (documentModel != null)
                {
                    switch (actionOP)
                    {
                        case BaseStruct.ActionOperationStruct.ADD_SAME:
                            {
                                ViewData["isChooseDept"] = true;//是否能选择发布单位
                                List<SelectListItem> radioPubitems = new List<SelectListItem>();
                                //发布单位
                                ViewData["defaultPubDept"] = "";
                                ViewData["defaulRadioChooseValue"] = "";
                                DataTable docClsAuthortiyDT = docClsAuthorityBLL.GetDeptInDodAuthority(entityNo, emplNo, docClsCd);
                                items = new List<SelectListItem>();

                                if (docClsAuthortiyDT.Rows.Count > 0)
                                {
                                    foreach (DataRow dr in docClsAuthortiyDT.Rows)
                                    {
                                        if (dr["FIsMainPosition"].ToString() == "Y")
                                        {
                                            items.Add(new SelectListItem() { Text = dr["FDeptName"].ToString(), Value = dr["FDeptNo"].ToString() });
                                            ViewData["defaultPubDept"] = dr["FDeptNo"].ToString();
                                            break;
                                        }
                                    }
                                    foreach (DataRow dr in docClsAuthortiyDT.Rows)
                                    {
                                        if (dr["FIsMainPosition"].ToString() == "N")
                                        {
                                            items.Add(new SelectListItem() { Text = dr["FDeptName"].ToString(), Value = dr["FDeptNo"].ToString() });
                                        }
                                    }
                                    DataRow[] dataRows = docClsAuthortiyDT.Select("FIsMainPosition='Y'");
                                    if (ViewData["defaultPubDept"].ToString() == "")
                                    {
                                        ViewData["defaultPubDept"] = docClsAuthortiyDT.Rows[0]["FDeptNo"].ToString();
                                    }
                                    radioPubitems.Add(new SelectListItem() { Text = "部门", Value = "0" });
                                }
                                ViewData["docPubDeptSelection"] = items;

                                //发布工作组
                                ViewData["defaultPubWorkGroup"] = "";
                                docClsAuthortiyDT = docClsAuthorityBLL.GetGroupInDodAuthority(entityNo, emplNo, docClsCd);
                                items = new List<SelectListItem>();
                                if (docClsAuthortiyDT.Rows.Count > 0)
                                {
                                    foreach (DataRow dr in docClsAuthortiyDT.Rows)
                                    {
                                        items.Add(new SelectListItem() { Text = dr["FWorkGrpName"].ToString(), Value = dr["FWorkGrpNo"].ToString() });
                                    }
                                    ViewData["defaultPubWorkGroup"] = docClsAuthortiyDT.Rows[0]["FWorkGrpNo"].ToString();
                                    radioPubitems.Add(new SelectListItem() { Text = "工作组", Value = "1" });
                                }
                                ViewData["docPubWorkGroupSelection"] = items;
                                ViewData["pubItemSelection"] = radioPubitems;
                                if (radioPubitems.Count > 0)
                                {
                                    ViewData["defaulRadioChooseValue"] = radioPubitems[0].Value;
                                }



                                documentModel.FEmpName = hrEmplBLL.GetEmpName(entityNo, emplNo);
                                documentModel.FPubDate = DateTime.Now;
                                if (docClsModel.FIsHomePageShowLimit == "Y")
                                {
                                    documentModel.FValidDate = docClsModel.FHomePageShowDays.HasValue ? DateTime.Now.AddDays(docClsModel.FHomePageShowDays.Value) : DateTime.Now;
                                }
                                documentModel.FThumbGenType = "2";
                                if (docClsModel.FDefaultEditMode == "H")
                                {
                                    if (sysTemplateList.Count > 0)
                                    {

                                        var tmpList = sysTemplateList.Where(s => s.FIsDefault == "Y");
                                        if (tmpList.Count() > 0)
                                        {
                                            ViewData["templateDefaultVlaue"] = tmpList.First().FTemplateID.ToString();
                                            documentModel.FContentTxt = System.Text.Encoding.Default.GetString(tmpList.First().FContent);
                                        }
                                        // ViewData["templateDefaultVlaue"] = sysTemplateList.First().FTemplateID.ToString();
                                    }

                                }
                                else
                                {
                                    if (docClsModel.FDefaultEditMode == "O")
                                    {
                                        if (sysTemplateList.Count > 0)
                                        {
                                            var tmpList = sysTemplateList.Where(s => s.FIsDefault == "Y");
                                            if (tmpList.Count() > 0)
                                            {
                                                ViewData["templateDefaultVlaue"] = tmpList.First().FFileName.ToString();

                                            }
                                        }
                                    }
                                }
                                //首页显示
                                documentModel.FIsShowHomePage = docClsModel.FDefaultShowValue;

                                //默认 在内网中显示
                                documentModel.IsToIntranetPlat = "Y";


                                break;
                            }

                        case BaseStruct.ActionOperationStruct.EDIT:
                            {
                                //if (docType == "PUB" || documentModel.FEmplNo == emplNo)
                                if (docType == "PUB" && documentModel.FEmplNo == emplNo)
                                {
                                    //发布人和修改人是同一人
                                    ViewData["isChooseDept"] = true;//是否能选择发布单位
                                    List<SelectListItem> radioPubitems = new List<SelectListItem>();
                                    //发布单位
                                    ViewData["defaultPubDept"] = "";
                                    ViewData["defaulRadioChooseValue"] = "";
                                    DataTable docClsAuthortiyDT = docClsAuthorityBLL.GetDeptInDodAuthority(entityNo, emplNo, docClsCd);
                                    items = new List<SelectListItem>();
                                    if (docClsAuthortiyDT.Rows.Count > 0)
                                    {
                                        foreach (DataRow dr in docClsAuthortiyDT.Rows)
                                        {
                                            items.Add(new SelectListItem() { Text = dr["FDeptName"].ToString(), Value = dr["FDeptNo"].ToString() });
                                        }
                                        ViewData["defaultPubDept"] = docClsAuthortiyDT.Rows[0]["FDeptNo"].ToString();
                                        radioPubitems.Add(new SelectListItem() { Text = "部门", Value = "0" });
                                    }
                                    ViewData["docPubDeptSelection"] = items;

                                    //发布工作组
                                    ViewData["defaultPubWorkGroup"] = "";
                                    docClsAuthortiyDT = docClsAuthorityBLL.GetGroupInDodAuthority(entityNo, emplNo, docClsCd);
                                    items = new List<SelectListItem>();
                                    if (docClsAuthortiyDT.Rows.Count > 0)
                                    {
                                        foreach (DataRow dr in docClsAuthortiyDT.Rows)
                                        {
                                            items.Add(new SelectListItem() { Text = dr["FWorkGrpName"].ToString(), Value = dr["FWorkGrpNo"].ToString() });
                                        }
                                        ViewData["defaultPubWorkGroup"] = docClsAuthortiyDT.Rows[0]["FWorkGrpNo"].ToString();
                                        radioPubitems.Add(new SelectListItem() { Text = "工作组", Value = "1" });
                                    }
                                    ViewData["docPubWorkGroupSelection"] = items;
                                    ViewData["pubItemSelection"] = radioPubitems;
                                    if (radioPubitems.Count > 0)
                                    {
                                        ViewData["defaulRadioChooseValue"] = radioPubitems[0].Value;
                                    }
                                }
                                else
                                {
                                    //发布人和修改人不是同一人
                                    ViewData["isChooseDept"] = false;//是否能选择发布单位
                                    List<SelectListItem> radioPubitems = new List<SelectListItem>();
                                    //发布单位
                                    ViewData["defaultPubDept"] = "";
                                    ViewData["defaulRadioChooseValue"] = "";
                                    items = new List<SelectListItem>();
                                    if (string.IsNullOrEmpty(documentModel.FDeptName))
                                    {
                                        documentModel.FDeptName = hrDeptBLL.GetDeptName(entityNo, documentModel.FDeptNo);
                                    }

                                    items.Add(new SelectListItem() { Text = documentModel.FDeptName, Value = documentModel.FDeptNo });
                                    ViewData["defaultPubDept"] = documentModel.FDeptNo;
                                    radioPubitems.Add(new SelectListItem() { Text = "部门", Value = "0" });
                                    ViewData["docPubDeptSelection"] = items;
                                    //发布工作组
                                    ViewData["defaultPubWorkGroup"] = "";
                                    items = new List<SelectListItem>();
                                    if (!string.IsNullOrEmpty(documentModel.FWorkGrpNo))
                                    {
                                        items.Add(new SelectListItem() { Text = documentModel.FWorkGrpName, Value = documentModel.FWorkGrpNo });
                                        ViewData["defaultPubWorkGroup"] = documentModel.FWorkGrpNo;
                                        radioPubitems.Add(new SelectListItem() { Text = "工作组", Value = "1" });
                                    }
                                    ViewData["docPubWorkGroupSelection"] = items;
                                    ViewData["pubItemSelection"] = radioPubitems;
                                    if (radioPubitems.Count > 0)
                                    {
                                        ViewData["defaulRadioChooseValue"] = radioPubitems[0].Value;
                                    }

                                }

                                if (string.IsNullOrEmpty(documentModel.FThumbGenType))
                                {
                                    documentModel.FThumbGenType = "2";
                                }
                                //发布部门/工作组
                                if (!string.IsNullOrEmpty(documentModel.FDeptNo))
                                {
                                    //部门
                                    ViewData["defaulRadioChooseValue"] = "0";
                                    ViewData["defaultPubDept"] = documentModel.FDeptNo;
                                }
                                else
                                {
                                    //工作组
                                    ViewData["defaulRadioChooseValue"] = "1";
                                    ViewData["defaultPubWorkGroup"] = documentModel.FWorkGrpNo;
                                }
                                //获取附件信息

                                List<Model.DocAttach> docAttachList = docAttachBLL.GetDocAttachListByDocID(docId, "DOC");
                                if (docAttachList.Count > 0)
                                {
                                    string attachJsonStr = "[";
                                    foreach (Model.DocAttach docAttachModel in docAttachList)
                                    {
                                        attachJsonStr += "{'attachID':'" + docAttachModel.FAttachID + "','title':'" + docAttachModel.FAttachOldFileName +
                                            "','desc':'" + docAttachModel.FAttachDesc + "','atthref':'" + docAttachModel.FAttachSvrFileName + "'},";
                                    }
                                    attachJsonStr = attachJsonStr.Substring(0, attachJsonStr.LastIndexOf(","));
                                    attachJsonStr += "]";
                                    attachJsonStr = attachJsonStr.Replace("'", "\"");
                                    ViewData["attachJsonString"] = attachJsonStr;
                                }

                                List<Model.DocAttach> docAttachPicList = docAttachBLL.GetDocAttachListByDocID(docId, "PIC");
                                if (docAttachPicList.Count > 0)
                                {
                                    string viewStr = "";

                                    viewStr += "<fieldset id='overPic'>";
                                    viewStr += "<legend style='font-size: 12px'>已保存的图片</legend>";
                                    viewStr += "<ul id='pic_list1' style='margin:5px;'>";
                                    foreach (Model.DocAttach docAttachModel in docAttachPicList)
                                    {
                                        string src = "";
                                        string orgSrc = docAttachModel.FAttachSvrFileName;
                                        src = orgSrc.Replace("s_", "ss_");

                                        viewStr += "<li id='pic_" + docAttachModel.FAttachID + "' ><img class='content' src='" + Url.Action("IndexImage", "DocumentPub", new { pt = src }) + "'><img class='delbutton' onclick='DelPic(" + docAttachModel.FAttachID + ")' src='" + Url.Content("~/Scripts/SWFUpload/images/fancy_close.png") + "'></li>";
                                    }
                                    viewStr += "</ul>";
                                    viewStr += "</fieldset>";

                                    ViewData["viewStr"] = viewStr;
                                }

                                if (documentModel.FEditMode == "H")
                                {
                                    //fkc模式
                                    ViewData["defaultEditMode"] = "0";
                                }
                                else
                                {
                                    string strSvrFileName = documentModel.FSvrFileName;
                                    int t = strSvrFileName.LastIndexOf('.');
                                    if (t != -1)
                                    {
                                        string strExten = strSvrFileName.Substring(t + 1);
                                        if (strExten == "doc" || strExten == "docx")
                                        {
                                            ViewData["defaultEditMode"] = "1";
                                        }
                                        else if (strExten == "xls" || strExten == "xlsx")
                                        {
                                            ViewData["defaultEditMode"] = "2";
                                        }
                                        else if (strExten == "ppt" || strExten == "pptx")
                                        {
                                            ViewData["defaultEditMode"] = "3";
                                        }
                                        ViewData["url"] = strSvrFileName;
                                    }
                                }
                                //通知对象

                                List<Model.DocRecObject> docRecObjectList = docRecObjectBLL.GetListByView(entityNo, docId);
                                List<object> jsonList = new List<object>();
                                if (docRecObjectList.Count > 0)
                                {
                                    //部门
                                    var tmpList = docRecObjectList.Where(s => s.FDeptNo != "" && s.FWorkGrpNo == "").ToList();
                                    List<CommonValueModel> commValueList = new List<CommonValueModel>();
                                    if (tmpList.Count() > 0)
                                    {
                                        foreach (Model.DocRecObject docRecModel in tmpList)
                                        {
                                            commValueList.Add(new CommonValueModel() { Text = docRecModel.FEmpName, Value = docRecModel.FEmplNo });
                                        }

                                        jsonList.Add(commValueList);
                                    }
                                    else
                                    {
                                        jsonList.Add(commValueList);
                                    }
                                    //工作组
                                    tmpList = docRecObjectList.Where(s => s.FDeptNo == "" && s.FWorkGrpNo != "").ToList();
                                    commValueList = new List<CommonValueModel>();
                                    if (tmpList.Count() > 0)
                                    {
                                        foreach (Model.DocRecObject docRecModel in tmpList)
                                        {
                                            commValueList.Add(new CommonValueModel() { Text = docRecModel.FEmpName, Value = docRecModel.FEmplNo });
                                        }

                                        jsonList.Add(commValueList);
                                    }
                                    else
                                    {
                                        jsonList.Add(commValueList);
                                    }

                                    ViewData["recObjectKeys"] = JsonConvert.SerializeObject(jsonList);
                                }
                                else
                                {
                                    ViewData["recObjectKeys"] = "";
                                }
                                //合发部门
                                List<Model.DocumentUnionPubEmpl> docUnionPubEmplList = documentUnionPubEmplBLL.GetModelList(entityNo, docId);
                                if (docUnionPubEmplList.Count > 0)
                                {
                                    List<CommonValueModel> commValueList = new List<CommonValueModel>();
                                    var q = from p in docUnionPubEmplList group p by p.FDeptNo into g select g;
                                    foreach (var gp in q)
                                    {
                                        int i = 0;
                                        foreach (var item in gp)
                                        {
                                            Model.DocumentUnionPubEmpl docUnionPubEmplModel = item as Model.DocumentUnionPubEmpl;
                                            if (i == 0)
                                            {
                                                string deptName = hrDeptBLL.GetDeptName(entityNo, docUnionPubEmplModel.FDeptNo);
                                                commValueList.Add(new CommonValueModel() { Text = deptName + ":" + docUnionPubEmplModel.FEmpName, Value = docUnionPubEmplModel.FEmplNo });

                                                i++;
                                            }
                                            else
                                            {
                                                commValueList.Add(new CommonValueModel() { Text = docUnionPubEmplModel.FEmpName, Value = docUnionPubEmplModel.FEmplNo });

                                            }

                                        }
                                    }

                                    ViewData["joinDeptUserKeys"] = JsonConvert.SerializeObject(commValueList);
                                }
                                else
                                {
                                    ViewData["joinDeptUserKeys"] = "";
                                }

                                //发布人名称
                                documentModel.FEmpName = hrEmplBLL.GetEmpName(entityNo, documentModel.FEmplNo);
                                if (!string.IsNullOrEmpty(documentModel.FAuditDeptNo))
                                {
                                    documentModel.FAuditEmpName = hrEmplBLL.GetEmpName(entityNo, documentModel.FEmplNo);
                                }
                                else
                                {
                                    documentModel.FAuditEmpName = hrEmplBLL.GetEmpName(entityNo, OperateSession.get(GlobalConstant.PARAM_FEMPLNO));
                                }

                                //呈送信息栏目
                                List<Model.DocReference> docReferenceList = docReferenceBLL.GetListByDocId(entityNo,docId );
                                if (docReferenceList.Count > 0)
                                {
                                    List<CommonValueModel> commValueList = new List<CommonValueModel>();
                                    foreach (Model.DocReference docReferenceModel in docReferenceList)
                                    {
                                        commValueList.Add(new CommonValueModel { Text = docReferenceModel.FDocClsName, Value = docReferenceModel.FDocClsCd });
                                    }

                                    ViewData["docReferenceClsJson"] = JsonConvert.SerializeObject(commValueList);
                                }
                                else
                                {
                                    ViewData["docReferenceClsJson"] = "";
                                }


                                //读取权限
                                documentAuthorityList = documentAuthorityBLL.GetModelListByFDocId(documentModel.FDocId);

                                break;
                            }
                    }
                }

                ViewData["hdMethod"] = actionOP;
                ViewData["docType"] = docType;
                DocumentPubEditViewModel docPutEditViewModel = new DocumentPubEditViewModel(documentModel, docClsModel,documentAuthorityList);
                return View("DocumentPubEdit", docPutEditViewModel);
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        ///  获取模板下拉框字符串
        /// </summary>
        /// <param name="docClsCd">信息类别编号</param>
        /// <param name="editMode">编辑模式</param>
        public string GetTemplateString(string docClsCd, string editMode)
        {
            string result = "";
            string entityNo = GlobalConstant.ENTITYNO;
            if (docClsCd != string.Empty && editMode != string.Empty)
            {
                List<Model.SysTemplate> sysTemplateList = sysTemplateBLL.GetListByTemplateType(entityNo, docClsCd, editMode);
                List<CommonValueModel> commonValueList = new List<CommonValueModel>();


                System.Text.StringBuilder sbr = new System.Text.StringBuilder();
                commonValueList.Add(new CommonValueModel() { Text = "清除模板", Value = "-1" });
                if (editMode == "H")
                {
                    foreach (Model.SysTemplate sysTemplateModel in sysTemplateList)
                    {
                        commonValueList.Add(new CommonValueModel() { Text = sysTemplateModel.FTitle, Value = sysTemplateModel.FTemplateID.ToString() });
                    }
                }
                else
                {
                    if (editMode == "O")
                    {
                        foreach (Model.SysTemplate sysTemplateModel in sysTemplateList)
                        {
                            commonValueList.Add(new CommonValueModel() { Text = sysTemplateModel.FTitle, Value = sysTemplateModel.FFileName.ToString() });
                        }
                    }
                }
                result = JsonConvert.SerializeObject(commonValueList);
            }
            return result;
        }
        /// <summary>
        /// 获取HTML模板内容
        /// </summary>
        /// <param name="templateID"></param>
        /// <returns>HTML字符串</returns>
        public string GetTemplateHtml(decimal templateID)
        {
            string result = "";
            if (decimal.TryParse(templateID.ToString(), out templateID))
            {
                Model.SysTemplate sysTemplateModel = sysTemplateBLL.GetModel(templateID);
                if (sysTemplateModel != null)
                {
                    result = System.Text.Encoding.Default.GetString(sysTemplateModel.FContent);
                }
            }
            return result;
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="docClsModel">信息类别实体类</param>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Save(Model.Document documentModel)
        {
            ViewData["pageIndex"] = Fetch.Post("hdPageIndex");
            bool isSuccess = true;
            string errorMessage = "";
            ActionResult actionResult = null;
            string entityNo = GlobalConstant.ENTITYNO;
            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
            Model.Document newDocumentModel = new Model.Document();
            //基本信息
            newDocumentModel.FDocClsCd = Fetch.Post("hdDocClsCd");
            Model.DocCls docClsModel = docClsBLL.GetModel(entityNo, newDocumentModel.FDocClsCd);
            if (docClsModel != null)
            {
                newDocumentModel.FEntityNo = GlobalConstant.ENTITYNO;
                newDocumentModel.FPubDate = DateTime.Now;
                newDocumentModel.FPubIp = Common.GenerateUtil.GetClientIPv4Address();
                newDocumentModel.FSubTitle = documentModel.FSubTitle;
                newDocumentModel.FAuthor = documentModel.FAuthor;
                //newDocumentModel.FReadCnt = 1;

                newDocumentModel.FEditMode = RadioButtonListExtension.GetValue<string>("rdEditMode") == "0" ? "H" : "O";
                newDocumentModel.FTitle = documentModel.FTitle;
                if (newDocumentModel.FEditMode == "H")
                {
                    newDocumentModel.FContentTxt = Fetch.Post("hdfckValue");
                }
                newDocumentModel.FIsTop = Fetch.Post("FIsTop") == "C" ? 1 : 0;

                //数据逻辑验证
                if (newDocumentModel.FDocClsCd == "")
                {
                    errorMessage = "信息类别编号不能为空";
                    isSuccess = false;
                }
                if (isSuccess)
                {
                    if (newDocumentModel.FTitle == "")
                    {
                        errorMessage = "信息标题不能为空";
                        isSuccess = false;
                    }
                }
                if (docClsModel.FIsNeedAudit == "Y")
                {
                    newDocumentModel.FStatus = "N";
                }
                else
                {
                    newDocumentModel.FStatus = "Y";
                    newDocumentModel.FIsEnroll = "Y";
                    newDocumentModel.FAuditDate = DateTime.Now;
                }
                if (docClsModel.FIsShowHomePageCtrl == "N")
                {
                    newDocumentModel.FIsShowHomePage = "Y";
                }
                else
                {
                    newDocumentModel.FIsShowHomePage = Fetch.Post("FIsShowHomePage") == "C" ? "Y" : "N";
                }

                if (docClsModel.FIsHomePageShowLimit == "Y")
                {
                    newDocumentModel.FValidDate = documentModel.FValidDate;
                }

                string rdPubDeptValue = Fetch.Post("rdPubDept");

                if (rdPubDeptValue == "0")
                {
                    string cboPubDeptValue = Fetch.Post("cboPubDept_VI");
                    newDocumentModel.FDeptNo = cboPubDeptValue;
                }
                else
                {
                    string cboPubWorkGroup = Fetch.Post("cboPubWorkGroup_VI");
                    newDocumentModel.FWorkGrpNo = cboPubWorkGroup;
                }


                if (docClsModel.FIsReferenceNo == "Y")
                {
                    newDocumentModel.FReferenceNo = documentModel.FReferenceNo;
                }
                newDocumentModel.FRecycle = documentModel.FRecycle;

                //推送到财政公共服务平台
                if (documentModel.IsToFinancePlat != null)
                {
                    newDocumentModel.IsToFinancePlat = documentModel.IsToFinancePlat.ToLower() == "true" ? "Y" : "N";
                }
                else
                {
                    newDocumentModel.IsToFinancePlat = "N";
                }
                //是否在内网中显示
                if (documentModel.IsToIntranetPlat != null)
                {
                    newDocumentModel.IsToIntranetPlat = documentModel.IsToIntranetPlat.ToLower() == "true" ? "Y" : "N";
                }
                else
                {
                    newDocumentModel.IsToIntranetPlat = "N";
                }
                newDocumentModel.FDownTitle = documentModel.FDownTitle;
                newDocumentModel.FDownDateString = documentModel.FDownDateString;


                List<Model.DocAttach> docAttachList = new List<Model.DocAttach>();//附件，如上传失败，原先上传的文件也已经删除

                //所有上传图片
                List<Model.DocAttach> docAttachPicList = new List<Model.DocAttach>();
                //原来上传图片
                List<Model.DocAttach> docAttachPicOldList = new List<Model.DocAttach>();
                if (Fetch.Post("hdMethod") == BaseStruct.ActionOperationStruct.EDIT)
                {
                    docAttachPicOldList = docAttachBLL.GetDocAttachListByDocID(decimal.Parse(Fetch.Post("hdDocId")), "PIC");
                    docAttachPicList.AddRange(docAttachPicOldList);
                }
                //上传图片
                List<Model.DocAttach> docAttachPicNewList = new List<Model.DocAttach>();
                if (isSuccess)
                {
                    docAttachPicNewList = UploadPicAttach(ref newDocumentModel, docClsModel, documentModel, ref errorMessage, ref isSuccess);
                    docAttachPicList.AddRange(docAttachPicNewList);
                }


                string chkSLTValue = Fetch.Post("chkSLT") == "C" ? "Y" : "N";
                if (isSuccess)
                {

                    if (docClsModel.FIsPicNews == 1 && chkSLTValue == "Y")
                    {
                        UploadBreviaryImg(ref newDocumentModel, docClsModel, documentModel, ref errorMessage, ref isSuccess, docAttachPicList);
                    }
                }
                if (isSuccess)
                {
                    docAttachList = UploadAttch(ref newDocumentModel, docClsModel, documentModel, ref errorMessage, ref isSuccess);

                    //上传图片加入到附件
                    if (docAttachPicNewList.Count > 0)
                    {
                        docAttachList.AddRange(docAttachPicNewList);
                    }

                    if (!isSuccess)
                    {
                        //上传失败删除缩略图
                        if (docClsModel.FIsPicNews == 1 && chkSLTValue == "Y")
                        {
                            GenerateUtil.DeleteFile(newDocumentModel.FThumbSrvFileName);
                        }
                    }
                    if (newDocumentModel.FEditMode == "O")
                    {
                        UploadOffice(ref newDocumentModel, docClsModel, documentModel, ref errorMessage, ref isSuccess);

                    }
                    if (!isSuccess)
                    {
                        //上传失败删除缩略图
                        if (docClsModel.FIsPicNews == 1 && chkSLTValue == "Y")
                        {
                            GenerateUtil.DeleteFile(newDocumentModel.FThumbSrvFileName);
                        }
                        //上传失败删除附件
                        //删除附件
                        foreach (Model.DocAttach docAttachModel in docAttachList)
                        {
                            GenerateUtil.DeleteFile(docAttachModel.FAttachSvrFileName);
                        }
                    }
                    List<Model.DocRecObject> docRecObjectList = new List<Model.DocRecObject>();
                    DataTable emplDT = hrEmplPositionBLL.GetMainDeptEmplALL(entityNo);//所有人员DataTable对象
                    if (isSuccess)
                    {
                        //通知对象
                        string recObjString = Fetch.Post("hdSelRecObjectKeys");
                        if (recObjString != "")
                        {
                            JArray deserializedString = (JArray)JsonConvert.DeserializeObject(recObjString);
                            //部门人员
                            List<CommonValueModel> commonValueList = JsonConvert.DeserializeObject<List<CommonValueModel>>(deserializedString[0].ToString());
                            if (commonValueList.Count > 0)
                            {

                                foreach (CommonValueModel commonValue in commonValueList)
                                {
                                    Model.DocRecObject docRecObjectModel = new Model.DocRecObject();
                                    List<DataRow> empDRList = (from c in emplDT.AsEnumerable()
                                                               where c.Field<string>("FEmplNo") == commonValue.Value
                                                               select c).ToList();
                                    if (empDRList.Count() > 0)
                                    {
                                        docRecObjectModel.FDeptNo = empDRList[0]["FDeptNo"].ToString();
                                        docRecObjectModel.FEmplNo = commonValue.Value;
                                        docRecObjectModel.FEntityNo = entityNo;
                                        docRecObjectList.Add(docRecObjectModel);
                                    }
                                }
                            }

                            //工作组人员
                            commonValueList = JsonConvert.DeserializeObject<List<CommonValueModel>>(deserializedString[1].ToString());
                            if (commonValueList.Count > 0)
                            {
                                DataTable emplWorkGroupDT = hrWorkGrpMemberBLL.GetWorkGrpEmplNoSByView(entityNo);
                                foreach (CommonValueModel commonValue in commonValueList)
                                {
                                    Model.DocRecObject docRecObjectModel = new Model.DocRecObject();
                                    List<DataRow> empDRList = (from c in emplWorkGroupDT.AsEnumerable()
                                                               where c.Field<string>("FEmplNo") == commonValue.Value
                                                               select c).ToList();
                                    if (empDRList.Count() > 0)
                                    {
                                        docRecObjectModel.FWorkGrpNo = empDRList[0]["FWorkGrpNo"].ToString();
                                        docRecObjectModel.FEmplNo = commonValue.Value;
                                        docRecObjectModel.FEntityNo = entityNo;
                                        docRecObjectList.Add(docRecObjectModel);
                                    }
                                }
                            }
                        }
                    }
                    List<Model.DocumentUnionPubEmpl> documentUnionPubEmplList = new List<Model.DocumentUnionPubEmpl>();
                    if (isSuccess)
                    {
                        //合发部门
                        string joinDeptUserString = Fetch.Post("hdSelJoinDeptUserKeys");
                        if (joinDeptUserString != "")
                        {
                            List<CommonValueModel> commonValueList = JsonConvert.DeserializeObject<List<CommonValueModel>>(joinDeptUserString);
                            foreach (CommonValueModel commonValue in commonValueList)
                            {
                                Model.DocumentUnionPubEmpl docUnionPubEmplModel = new Model.DocumentUnionPubEmpl();
                                List<DataRow> empDRList = (from c in emplDT.AsEnumerable()
                                                           where c.Field<string>("FEmplNo") == commonValue.Value
                                                           select c).ToList();
                                if (empDRList.Count() > 0)
                                {
                                    docUnionPubEmplModel.FDeptNo = empDRList[0]["FDeptNo"].ToString();
                                    docUnionPubEmplModel.FDocId = documentModel.FDocId;
                                    docUnionPubEmplModel.FEmplNo = commonValue.Value;
                                    docUnionPubEmplModel.FEntityNo = entityNo;
                                    documentUnionPubEmplList.Add(docUnionPubEmplModel);
                                }

                            }
                        }
                    }
                    //呈送信息栏目
                    List<Model.DocReference> docReferenceList = new List<Model.DocReference>();
                    if (isSuccess)
                    {
                        string docReferenceClsString = Fetch.Post("hdDocReferenceCls");
                        if (docReferenceClsString != "")
                        {
                            List<CommonValueModel> commonValueList = JsonConvert.DeserializeObject<List<CommonValueModel>>(docReferenceClsString);
                            foreach (CommonValueModel commonValue in commonValueList)
                            {
                                Model.DocReference docReferenceModel = new Model.DocReference()
                                {
                                    FDocClsCd = commonValue.Value
                                };
                                docReferenceList.Add(docReferenceModel);
                            }
                        }
                    }

                    //文档查看权限
                    List<Model.documentAuthority> documentAuthorityList = new List<Model.documentAuthority>();
                    if (Fetch.Post("hdShowLookTab") == "Y")
                    {
                        //查看权限
                        GenerateClsAuthorityList("Look", "LOOK", entityNo, ref documentAuthorityList);
                    }


                    if (isSuccess)
                    {
                        if (newDocumentModel.FContentTxt != null)
                        {
                            if (newDocumentModel.FContentTxt.IndexOf("<img") != -1 || newDocumentModel.FContentTxt.IndexOf("<IMG") != -1)
                            {
                                newDocumentModel.FContentIsImg = "Y";
                            }
                        }
                        else
                        {
                            newDocumentModel.FContentIsImg = "N";
                        }
                        string gridDocClsCd = Fetch.Post("hdGridDocClsCd");
                        switch (Fetch.Post("hdMethod"))
                        {
                            case BaseStruct.ActionOperationStruct.EDIT:
                                {
                                    //修改
                                    //newDocumentModel.FEmplNo = documentModel.FEmplNo;
                                    //int pageIndex = ViewData["pageIndex"] == null ? 1 : int.Parse(ViewData["pageIndex"].ToString());
                                    int pageIndex = Fetch.Post("hdPageIndex") == "" ? 1 : int.Parse(Fetch.Post("hdPageIndex").ToString());

                                    newDocumentModel.FDocId = decimal.Parse(Fetch.Post("hdDocId"));
                                    if (Fetch.Post("hdDocType") == "AUDIT")
                                    {
                                        //string IsEnroll = Fetch.Post("FIsEnroll");
                                        string IsEnroll = RadioButtonListExtension.GetValue<string>("FIsEnroll");
                                        if (string.IsNullOrEmpty(IsEnroll))
                                        {
                                            newDocumentModel.FStatus = "N";

                                        }
                                        else
                                        {
                                            newDocumentModel.FStatus = "Y";
                                            newDocumentModel.FIsEnroll = IsEnroll;
                                            Model.Document oldDocModel = documentBLL.GetModel(newDocumentModel.FDocId);

                                            if (oldDocModel != null && (oldDocModel.FStatus != newDocumentModel.FStatus || oldDocModel.FIsEnroll != newDocumentModel.FIsEnroll))
                                            {
                                                newDocumentModel.FAuditDate = DateTime.Now;
                                                newDocumentModel.FAuditDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                                                newDocumentModel.FAuditEmpNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                                                newDocumentModel.FAuditIP = Common.GenerateUtil.GetClientIPv4Address();
                                            }
                                            else
                                            {
                                                newDocumentModel.FAuditDate = oldDocModel.FAuditDate;
                                                newDocumentModel.FAuditDeptNo = oldDocModel.FAuditDeptNo;
                                                newDocumentModel.FAuditEmpNo = oldDocModel.FAuditEmpNo;
                                                newDocumentModel.FAuditIP = oldDocModel.FAuditIP;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        Model.Document tmpDocModel = documentBLL.GetModel(newDocumentModel.FDocId);
                                        newDocumentModel.FAuditDate = tmpDocModel.FAuditDate;
                                        newDocumentModel.FAuditDeptNo = tmpDocModel.FAuditDeptNo;
                                        newDocumentModel.FAuditEmpNo = tmpDocModel.FAuditEmpNo;
                                        newDocumentModel.FAuditIP = tmpDocModel.FAuditIP;
                                        newDocumentModel.FStatus = tmpDocModel.FStatus;
                                        newDocumentModel.FIsEnroll = tmpDocModel.FIsEnroll;
                                    }

                                    string isTop = newDocumentModel.FIsTop == 1 ? "TOP" : "";
                                    newDocumentModel.FUpdDate = DateTime.Now;
                                    newDocumentModel.FUpdDeptNo = OperateSession.get(GlobalConstant.PARAM_DEPTNO);
                                    newDocumentModel.FUpdEmplNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                                    newDocumentModel.FUpdIP = Common.GenerateUtil.GetClientIPv4Address();
                                    try
                                    {
                                        string isPubJCMS = Fetch.Post("FIsPubJCMS") == "C" ? "Y" : "N";
                                        newDocumentModel.FIsPubJCMS = isPubJCMS;
                                        Model.Document oldDocModel = documentBLL.GetModel(newDocumentModel.FDocId);
                                        if (isPubJCMS == "Y")
                                        {
                                            if (docClsModel.FJCMSColID.HasValue)
                                            {
                                                newDocumentModel.FParallelDocClsCd = docClsModel.FJCMSColID.Value.ToString();
                                            }
                                        }
                                        else
                                        {
                                            newDocumentModel.FParallelDocClsCd = oldDocModel.FParallelDocClsCd;
                                        }

                                        documentBLL.UpdateDocAndAttach(newDocumentModel, docAttachList, docRecObjectList, isTop, documentUnionPubEmplList, docReferenceList, documentAuthorityList);
                                        //修改成功,判断是否需要推送JCMS

                                        Model.Document docModel = documentBLL.GetModel(newDocumentModel.FDocId);
                                        if (isPubJCMS == "Y")
                                        {
                                            Common.GenerateUtil.PulishToJcms(docModel, docModel.FDocClsCd);
                                        }
                                        GenerateDocStaticHtml(docModel.FDocClsCd);
                                        if (newDocumentModel.FEditMode == "H")
                                        {
                                            if (Fetch.Post("hdDocType") == "PUB")
                                            {
                                                ViewData["RedirectURL"] = Url.Action("DocumentList", "DocumentPub", new
                                                {
                                                    docClsCd = gridDocClsCd,
                                                    id = pageIndex
                                                });
                                            }
                                            else
                                            {
                                                if (Fetch.Post("hdDocType") == "MANAGE")
                                                {
                                                    ViewData["RedirectURL"] = Url.Action("DocumentList", "DocumentManage", new
                                                    {
                                                        docClsCd = gridDocClsCd,
                                                        id = pageIndex
                                                    });
                                                }
                                                else
                                                {
                                                    if (Fetch.Post("hdDocType") == "AUDIT")
                                                    {
                                                        ViewData["RedirectURL"] = Url.Action("DocumentList", "DocumentAudit", new
                                                        {
                                                            docClsCd = gridDocClsCd,
                                                            id = pageIndex
                                                        });
                                                    }
                                                }
                                            }
                                            actionResult = View("SuccessMessagePage");
                                        }
                                        else
                                        {
                                            if (Fetch.Post("hdDocType") == "PUB")
                                            {
                                                string strUrl = Url.Action("DocumentList", "DocumentPub", new
                                                {
                                                    docClsCd = gridDocClsCd,
                                                    id = pageIndex
                                                });
                                                Response.Write("ok|" + strUrl);
                                                Response.Flush();
                                                Response.End();
                                            }
                                            else
                                            {
                                                if (Fetch.Post("hdDocType") == "MANAGE")
                                                {
                                                    string strUrl = Url.Action("DocumentList", "DocumentManage", new
                                                    {
                                                        docClsCd = gridDocClsCd,
                                                        id = pageIndex
                                                    });
                                                    Response.Write("ok|" + strUrl);
                                                    Response.Flush();
                                                    Response.End();
                                                }
                                                else
                                                {
                                                    if (Fetch.Post("hdDocType") == "AUDIT")
                                                    {
                                                        string strUrl = Url.Action("DocumentList", "DocumentAudit", new
                                                        {
                                                            docClsCd = gridDocClsCd,
                                                            id = pageIndex
                                                        });
                                                        Response.Write("ok|" + strUrl);
                                                        Response.Flush();
                                                        Response.End();
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ee)
                                    {
                                        errorMessage = "信息修改失败" + ee.Message;
                                        isSuccess = false;
                                    }
                                    if (actionResult == null)
                                    {
                                        actionResult = DocumentPubEdit(0, docClsModel.FDocClsCd, Fetch.Post("hdMethod"), errorMessage, newDocumentModel, Fetch.Post("hdDocType"));
                                    }
                                    break;
                                }
                            case BaseStruct.ActionOperationStruct.ADD_SAME:
                                {
                                    //增加
                                    try
                                    {
                                        newDocumentModel.FEmplNo = empNo;
                                        string isPubJCMS = Fetch.Post("FIsPubJCMS") == "C" ? "Y" : "N";
                                        newDocumentModel.FIsPubJCMS = isPubJCMS;

                                        Model.Document oldDocModel = documentBLL.GetModel(newDocumentModel.FDocId);
                                        if (isPubJCMS == "Y")
                                        {
                                            if (docClsModel.FJCMSColID.HasValue)
                                            {
                                                newDocumentModel.FParallelDocClsCd = docClsModel.FJCMSColID.Value.ToString();
                                            }
                                        }

                                        decimal decDocId = documentBLL.SaveDocumentAndAttach(newDocumentModel, docAttachList, docRecObjectList, documentUnionPubEmplList, docReferenceList, documentAuthorityList);
                                        //增加成功,判断是否需要推送JCMS

                                        Model.Document docModel = documentBLL.GetModel(decDocId);
                                        if (isPubJCMS == "Y")
                                        {
                                            Common.GenerateUtil.PulishToJcms(docModel, docModel.FDocClsCd);
                                        }
                                        GenerateDocStaticHtml(docModel.FDocClsCd);
                                        if (newDocumentModel.FEditMode == "O")//修改原来保存的文件名
                                        {
                                            string strSvrFileName = newDocumentModel.FSvrFileName;
                                            int t = strSvrFileName.LastIndexOf('.');
                                            if (t != -1)
                                            {
                                                string strExten = strSvrFileName.Substring(t);
                                                t = strSvrFileName.LastIndexOf('/');
                                                if (t != -1)
                                                {
                                                    string strPath = strSvrFileName.Substring(0, t + 1);
                                                    string strNewOfficeName = strPath + entityNo + "_" + decDocId + "_" + newDocumentModel.FTitle.Replace(":", "").Replace("：", "").Replace(" ", "") + strExten;
                                                    //移动文件方式重命名文件

                                                    System.IO.File.Move(Server.MapPath(strSvrFileName), Server.MapPath(strNewOfficeName));
                                                }
                                            }

                                        }
                                        if (newDocumentModel.FEditMode == "H")
                                        {
                                            ViewData["RedirectURL"] = Url.Action("DocumentList", "DocumentPub", new
                                            {
                                                docClsCd = gridDocClsCd,
                                                id = 1
                                            });
                                            actionResult = View("SuccessMessagePage");
                                        }
                                        else
                                        {
                                            string strUrl = Url.Action("DocumentList", "DocumentPub", new
                                            {
                                                docClsCd = gridDocClsCd,
                                                id = 1
                                            });
                                            Response.Write("ok|" + strUrl);
                                            Response.Flush();
                                            Response.End();
                                        }
                                    }
                                    catch (Exception ee)
                                    {
                                        errorMessage = "信息增加失败" + ee.Message;
                                        isSuccess = false;
                                    }
                                    if (actionResult == null)
                                    {
                                        actionResult = DocumentPubEdit(0, docClsModel.FDocClsCd, Fetch.Post("hdMethod"), errorMessage, newDocumentModel, Fetch.Post("hdDocType"));
                                    }
                                    break;
                                }
                        }

                    }
                }
            }
            else
            {
                errorMessage = "信息类别参数异常";
                isSuccess = false;
            }
            if (actionResult == null)
            {
                actionResult = DocumentPubEdit(0, newDocumentModel.FDocClsCd, Fetch.Post("hdMethod"), errorMessage, newDocumentModel, Fetch.Post("hdDocType"));
            }
            return actionResult;
        }

        /// <summary>
        /// 显示缩略图
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult IndexImage(string pt)
        {
            if (!string.IsNullOrEmpty(pt))
            {


                string strNewImgPath = Url.Content(pt);

                if (GenerateUtil.ExistsFile(strNewImgPath))//图片存在
                {
                    int width = 100;
                    int height = 100;
                    byte[] imgs = OperateImg.breviaryImg(width, height, strNewImgPath, 0);

                    Response.AppendHeader("Content-Length", imgs.Length.ToString());

                    //Response.Clear();
                    Response.ContentType = "image/jpeg";
                    Response.BinaryWrite(imgs);
                    Response.End();
                }
                else
                {
                    return View();
                }
            }
            else
            {
                return View();
            }
            return View();

        }
        /// <summary>
        /// 上传office文件，并取得相关数据
        /// </summary>
        /// <param name="newDocumentModel">新的文档对象</param>
        /// <param name="docClsModel">信息类别对象</param>
        /// <param name="documentModel">提交的文档对象</param>
        private void UploadOffice(ref Model.Document newDocumentModel, Model.DocCls docClsModel, Model.Document documentModel, ref string errorMessage, ref bool isSuccess)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            string docClsPath = docClsBLL.GetDocClsCdS(docClsModel.FDocClsCd, entityNo);//获取当前类别和其父类别组成的路径
            string savetype = Fetch.Post("savetype");//获取文件另存为格式类型 1,2,3...
            if (savetype != "" && savetype == "1")
            {
                //office文件保存路径
                string strOfficePath = Url.Content("~/Publish/" + entityNo + "/" + "DOC/" + docClsPath + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0'));
                //判断文件夹是否存在
                string strOfficeName = "";
                if (newDocumentModel.FDocId > 0)
                {
                    strOfficeName = entityNo + "_" + newDocumentModel.FDocId + "_" + newDocumentModel.FTitle.Replace(":", "").Replace("：", "").Replace(" ", "");
                }
                GenerateUtil.addfolder(strOfficePath);
                System.Web.HttpFileCollectionBase uploadFiles = Request.Files;
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    //上传附件
                    if (Request.Files[i].ContentLength > 0 && (uploadFiles.GetKey(i).ToUpper() == "EDITFILE"))
                    {
                        HttpPostedFileBase upload = Request.Files[i];
                        try
                        {
                            string imageFileName = Common.GenerateUtil.UploadFile(upload, strOfficePath, strOfficeName);
                            strOfficePath = strOfficePath + "/" + imageFileName;
                            newDocumentModel.FSvrFileName = strOfficePath;

                            //获取文件二进制格式
                            System.IO.Stream stream = upload.InputStream;
                            byte[] buffer = new byte[stream.Length];
                            stream.Read(buffer, 0, (int)stream.Length);
                            stream.Close();
                            newDocumentModel.FContentBin = buffer;
                        }
                        catch (Exception ee)
                        {
                            isSuccess = false;
                            errorMessage = "上传office文件保存失败" + ee.Message;
                        }
                    }
                }
            }
            else
            {
                isSuccess = false;
                errorMessage = "上传office文件失败";
            }




        }
        /// <summary>
        /// 上传缩略图，并取得相关数据
        /// </summary>
        /// <param name="newDocumentModel">新的文档对象</param>
        /// <param name="docClsModel">信息类别对象</param>
        /// <param name="documentModel">提交的文档对象</param>
        private List<Model.DocAttach> UploadAttch(ref Model.Document newDocumentModel, Model.DocCls docClsModel, Model.Document documentModel, ref string errorMessage, ref bool isSuccess)
        {
            List<Model.DocAttach> docAttachList = new List<Model.DocAttach>();
            string entityNo = GlobalConstant.ENTITYNO;
            string docClsPath = docClsBLL.GetDocClsCdS(docClsModel.FDocClsCd, entityNo);//获取当前类别和其父类别组成的路径
            //保存附件路径
            string strDefaultAttachPath = Url.Content("~/" + "Publish/" + entityNo + "/" + "attach/Doc/" + docClsPath + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0'));
            //路径不存在就创建文件夹
            GenerateUtil.addfolder(strDefaultAttachPath);

            string descFiles = Fetch.Post("fileDesc"); //取得描述
            List<string> descFileList = new List<string>();
            if (descFiles != "")
            {
                descFileList = descFiles.Split(new char[1] { ',' }).ToList();
                descFileList.RemoveAt(descFileList.Count - 1);

            }
            List<string> listImgPath = new List<string>();//保存图片路径，上传出错时删除文件

            System.Web.HttpFileCollectionBase uploadFiles = Request.Files;
            int j = 0;
            for (int i = 0; i < Request.Files.Count; i++)
            {
                //上传附件
                if (Request.Files[i].ContentLength > 0 && (uploadFiles.GetKey(i).ToUpper().Contains("UPLOADNAME")))
                {
                    HttpPostedFileBase upload = Request.Files[i];
                    string imageFileName = Common.GenerateUtil.UploadFile(upload, strDefaultAttachPath);
                    string strAttachPath = strDefaultAttachPath + "/" + imageFileName;
                    listImgPath.Add(strAttachPath);
                    switch (imageFileName)
                    {
                        case "1":
                            {
                                errorMessage = "上传文件内容为空";
                                break;
                            }
                        case "4":
                            {
                                errorMessage = "上传文件不能大于100M";
                                break;
                            }
                        case "5":
                            {
                                errorMessage = "上传文件已经存在";
                                break;
                            }
                    }
                    if (errorMessage == "")
                    {
                        string type = upload.ContentType;//获取文件类型
                        string factFileName = Path.GetFileNameWithoutExtension(upload.FileName);//获取文件名称
                        string extension = Path.GetExtension(upload.FileName).ToLower(); //获取文件的扩展名
                        //switch (extension)
                        //{
                        //    case ".jpg": type = "image/pjpeg"; break;
                        //    case ".gif": type = "image/gif"; break;
                        //    case ".bmp": type = "image/bm;"; break;
                        //    case ".png": type = "image/x-png"; break;
                        //}
                        //全路径


                        try
                        {



                            Model.DocAttach docAttachModel = new Model.DocAttach();
                            //获取文件二进制格式

                            System.IO.Stream stream = upload.InputStream;
                            byte[] buffer = new byte[stream.Length];
                            stream.Read(buffer, 0, (int)stream.Length);
                            stream.Close();
                            string docDesc = "";
                            if (j <= descFileList.Count - 1)
                            {
                                docDesc = descFileList[j];
                            }
                            docAttachModel.FEntityNo = entityNo;
                            docAttachModel.FAttachSvrFileName = strAttachPath;
                            docAttachModel.FAttachOldFileName = factFileName + extension;
                            docAttachModel.FAttachContent = buffer;
                            docAttachModel.FAttachFileExt = type;
                            docAttachModel.FAttachType = "DOC";
                            docAttachModel.FAttachDesc = docDesc;
                            docAttachList.Add(docAttachModel);
                            j++;
                        }
                        catch (Exception ee)
                        {
                            //删除原先上传的文件
                            if (listImgPath.Count > 0)
                            {
                                foreach (string str in listImgPath)
                                {
                                    GenerateUtil.DeleteFile(str);
                                }
                            }

                            errorMessage = "上传附件失败" + ee.Message;
                            isSuccess = false;
                        }

                    }
                }
            }
            return docAttachList;
        }


        /// <summary>
        /// 获取上传图片
        /// </summary>
        /// <param name="newDocumentModel"></param>
        /// <param name="docClsModel"></param>
        /// <param name="documentModel"></param>
        /// <param name="errorMessage"></param>
        /// <param name="isSuccess"></param>
        /// <returns></returns>
        private List<Model.DocAttach> UploadPicAttach(ref Model.Document newDocumentModel, Model.DocCls docClsModel, Model.Document documentModel, ref string errorMessage, ref bool isSuccess)
        {
            List<Model.DocAttach> docAttachList = new List<Model.DocAttach>();
            string entityNo = GlobalConstant.ENTITYNO;
            BLL.Entity entityBLL = new BLL.Entity();
            Model.Entity entityNoModel = entityBLL.GetModel(entityNo);
            string docClsPath = docClsBLL.GetDocClsCdS(docClsModel.FDocClsCd, entityNo);//获取当前类别和其父类别组成的路径
            //保存附件路径
            string strDefaultAttachPath = Url.Content("~/" + "Publish/" + entityNo + "/" + "attach/Pic/" + docClsPath + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0') + "/");
            //路径不存在就创建文件夹
            GenerateUtil.addfolder(strDefaultAttachPath);
            string nameDefault = "";

            //原来图片
            string strYuanlaiPath = strDefaultAttachPath + "yuanlai/";
            //路径不存在就创建文件夹
            GenerateUtil.addfolder(strYuanlaiPath);
            string nameYuanlai = "";



            try
            {
                if (PicStore.ThumbList != null)
                {
                    foreach (Thumbnail thumbModel in PicStore.ThumbList)
                    {
                        //获取文件的扩展名
                        string extension = Path.GetExtension(thumbModel.Name).ToLower();
                        //写入原图
                        nameYuanlai = thumbModel.ID + extension;
                        FileStream fs1 = new FileStream(Server.MapPath(strYuanlaiPath + nameYuanlai), FileMode.Create);
                        BinaryWriter bw1 = new BinaryWriter(fs1);
                        bw1.Write(thumbModel.OriginalData);
                        bw1.Close();
                        fs1.Close();

                        //改变文件名称
                        string strnewFileName = "";
                        strnewFileName = "s_" + GenerateUtil.GenerateStringId();
                        nameDefault = strnewFileName + extension;

                        //小图名称
                        string nameSmall = "s" + nameDefault;

                        //生成显示图片
                        if (thumbModel.OldWidth > 600)
                        {
                            int s_Width = 600;
                            int s_Height = thumbModel.OldHeight * s_Width / thumbModel.OldWidth;

                            BreviaryImg.SetImg(strYuanlaiPath + nameYuanlai, strDefaultAttachPath + nameDefault, s_Width, s_Height, 1, 2, int.Parse(entityNoModel.FWaterMarkCls), entityNo, string.Empty, 1, 1);
                        }
                        else
                        {

                            //生成缩略图
                            BreviaryImg.SetImg(strYuanlaiPath + nameYuanlai, strDefaultAttachPath + nameDefault, thumbModel.OldWidth, thumbModel.OldHeight, 1, 2, int.Parse(entityNoModel.FWaterMarkCls), entityNo, string.Empty, 1, 1);
                        }
                        //删除原来图片
                        GenerateUtil.DeleteFile(strYuanlaiPath + nameYuanlai);

                        //生成后台显示的小图
                        FileStream fs2 = new FileStream(Server.MapPath(Url.Content(strDefaultAttachPath)) + nameSmall, FileMode.Create);
                        BinaryWriter bw2 = new BinaryWriter(fs2);
                       bw2.Write(thumbModel.Data);
                        bw2.Close();
                        fs2.Close();

                        Model.DocAttach docAttachModel = new Model.DocAttach();

                        docAttachModel.FEntityNo = entityNo;
                        docAttachModel.FAttachSvrFileName = strDefaultAttachPath + strnewFileName + extension;
                        docAttachModel.FAttachOldFileName = thumbModel.Name;
                        docAttachModel.FAttachContent = thumbModel.Data;
                        docAttachModel.FAttachFileExt = extension;
                        docAttachModel.FAttachType = "PIC";
                        docAttachModel.FAttachDesc = "";
                        docAttachList.Add(docAttachModel);
                    }
                }
                PicStore.ThumbList = null;
                isSuccess = true;
            }
            catch (Exception ex)
            {
                PicStore.ThumbList = null;
                errorMessage = ex.ToString();
                isSuccess = false;
            }
            return docAttachList;
        }

        /// <summary>
        /// 上传缩略图，并取得相关数据
        /// </summary>
        /// <param name="newDocumentModel">新的文档对象</param>
        /// <param name="docClsModel">信息类别对象</param>
        /// <param name="documentModel">提交的文档对象</param>
        private void UploadBreviaryImg(ref Model.Document newDocumentModel, Model.DocCls docClsModel, Model.Document documentModel, ref string errorMessage, ref bool isSuccess, List<Model.DocAttach> docAttachPicList)
        {
            string entityNo = GlobalConstant.ENTITYNO;
            int imgWidth = docClsModel.FPicWidth; //缩图图宽
            int imgHeight = docClsModel.FPicHeight;//缩略图高
            int isWater = (int)docClsModel.FIsPicWaterMark;//是否加水印

            int WaterMarkCls = int.Parse(docClsModel.FWaterMarkCls);//水印类型
            string strWaterMarkPos = docClsModel.FWaterMarkPos;//水印位置
            int LeftRightMargin = docClsModel.FLeftRightMargin;//水印左右边距
            int TopBottomMargin = docClsModel.FTopBottomMargin;//水印上下边距
            //缩略图存放路径
            string docClsPath = docClsBLL.GetDocClsCdS(docClsModel.FDocClsCd, entityNo);//获取当前类别和其父类别组成的路径
            string strBreviaryImgPath = Url.Content("~/Publish/" + entityNo + "/DOC/" + docClsPath + "/" + DateTime.Now.Year + "/" + DateTime.Now.Month.ToString().PadLeft(2, '0'));
            //路径不存在就创建文件夹
            GenerateUtil.addfolder(strBreviaryImgPath);
            string strImgName = GenerateUtil.GenerateStringId() + ".jpg";//生成随机的缩略图名称，缩略图都保存为jpg格式
            strBreviaryImgPath += "/" + strImgName;//组合完整的缩略图路径
            newDocumentModel.FThumbFileExt = "image/pjpeg";
            newDocumentModel.FThumbSrvFileName = strBreviaryImgPath;//缩略图服务器路径
            newDocumentModel.FThumbGenType = Fetch.Post("cboThumbGenType_VI");//缩略图产生方式

            string strYImgPath = Fetch.Post("hdSltYLJ");




            string chkTQTPDZValue = Fetch.Post("chkTQTPDZ") == "C" ? "Y" : "N";//选取图片地址模式
            if (chkTQTPDZValue == "Y")
            {
                string thumbSeq = Fetch.Post("FThumbSeqID");
                int decThumbSeq = 0;
                if (thumbSeq != "")
                {
                    decThumbSeq = int.Parse(thumbSeq.Trim()) - 1;
                }
                if (docAttachPicList.Count > 0)
                {
                    //有上传图片，则提取上传图片的第一张图片
                    string svrFileName = docAttachPicList[decThumbSeq].FAttachSvrFileName;
                    if (!GenerateUtil.ExistsFile(svrFileName))
                    {
                        //文件不存在,判断是否是加了虚拟目录名的关系，是的话就去掉虚拟目录名称
                        svrFileName = GenerateUtil.GetPath(svrFileName);
                    }
                    if (GenerateUtil.ExistsFile(svrFileName))//有图片地址
                    {
                        try
                        {
                            isWater = 2;
                            //生成缩略图
                            BreviaryImg.SetImg(svrFileName, strBreviaryImgPath, imgWidth, imgHeight, int.Parse(newDocumentModel.FThumbGenType), isWater, WaterMarkCls, newDocumentModel.FEntityNo, strWaterMarkPos, LeftRightMargin, TopBottomMargin);
                        }
                        catch (Exception ee)
                        {
                            errorMessage = "生成缩略图异常" + ee.Message;
                            isSuccess = false;
                        }

                        newDocumentModel.FThumbSeqID = decThumbSeq + 1;//序号      
                        //获取图片二进制流
                        newDocumentModel.FThumbContent = UploadControlHelper.GetImgByte(strBreviaryImgPath);
                        newDocumentModel.FThumbOldFileName = UploadControlHelper.GetLoadImageName(svrFileName);//获取图片原名
                    }
                }
                else
                {

                    //自动提取
                    //判断文件是否存在
                    if (!GenerateUtil.ExistsFile(strYImgPath))
                    {
                        //文件不存在,判断是否是加了虚拟目录名的关系，是的话就去掉虚拟目录名称
                        strYImgPath = GenerateUtil.GetPath(strYImgPath);
                    }
                    if (GenerateUtil.ExistsFile(strYImgPath))//有图片地址
                    {
                        try
                        {
                            isWater = 2;
                            //生成缩略图
                            BreviaryImg.SetImg(strYImgPath, strBreviaryImgPath, imgWidth, imgHeight, int.Parse(newDocumentModel.FThumbGenType), isWater, WaterMarkCls, newDocumentModel.FEntityNo, strWaterMarkPos, LeftRightMargin, TopBottomMargin);

                        }
                        catch (Exception ee)
                        {
                            errorMessage = "生成缩略图异常" + ee.Message;
                            isSuccess = false;
                        }

                        newDocumentModel.FThumbSeqID = decThumbSeq + 1;//序号      
                        //获取图片二进制流
                        newDocumentModel.FThumbContent = UploadControlHelper.GetImgByte(strBreviaryImgPath);
                        newDocumentModel.FThumbOldFileName = UploadControlHelper.GetLoadImageName(strYImgPath);//获取图片原名
                    }
                }
            }
            else
            {
                //手动上传
                //logo图片
                UploadedFile[] fileList = UploadControlExtension.GetUploadedFiles("logoUpload");
                if (fileList.Count() > 0)
                {
                    UploadedFile upload = fileList[0];
                    if (upload.FileBytes.Length > 0)
                    {
                        string strUrl = Url.Content("~/Publish/" + entityNo + "/image");
                        string imageFileName = Common.GenerateUtil.UploadImage(upload, strUrl);
                        switch (imageFileName)
                        {
                            case "1":
                                {
                                    errorMessage = "上传文件内容为空";
                                    break;
                                }
                            case "2":
                                {
                                    errorMessage = "上传类型不是图片";
                                    break;
                                }
                            case "3":
                                {
                                    errorMessage = "请上传图片类型";
                                    break;
                                }
                            case "4":
                                {
                                    errorMessage = "上传文件不能大于10M";
                                    break;
                                }
                            case "5":
                                {
                                    errorMessage = "上传文件已经存在";
                                    break;
                                }
                        }
                        if (errorMessage == "")
                        {
                            string imageLoadPath = strUrl + "/" + imageFileName;
                            try
                            {
                                isWater = 2;
                                //生成缩略图
                                BreviaryImg.SetImg(imageLoadPath, strBreviaryImgPath, imgWidth, imgHeight, 2, isWater, WaterMarkCls, entityNo, strWaterMarkPos, LeftRightMargin, TopBottomMargin);
                            }
                            catch (Exception ee)
                            {
                                errorMessage = "生成缩略图异常" + ee.Message;
                                isSuccess = false;
                                GenerateUtil.DeleteFile(imageLoadPath);//删除老的图片
                            }
                            newDocumentModel.FThumbSeqID = null;

                            newDocumentModel.FThumbContent = upload.FileBytes;
                            //原图名称
                            newDocumentModel.FThumbOldFileName = Path.GetFileNameWithoutExtension(upload.FileName) + Path.GetExtension(upload.FileName).ToLower();
                            GenerateUtil.DeleteFile(imageLoadPath);//删除老的图片
                        }
                    }
                }

            }
        }


        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="attachID_En"></param>
        /// <returns></returns>
        [HttpPost]
        public string DeleteDocAttach(decimal attachID)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";

            try
            {

                string fileSvrPath = docAttachBLL.GetAttachSvrAddress(attachID);
                docAttachBLL.DeleteDocAttach(attachID);
                //删除文件
                try
                {
                    GenerateUtil.DeleteFile(fileSvrPath);
                }
                catch (Exception ee)
                {
                    errorMessage = "操作异常:" + ee.Message;
                }

                jsonstr = "SUCCESS";
            }
            catch (Exception ee)
            {
                errorMessage = "操作异常:" + ee.Message;
            }

            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
        /// <summary>
        /// 删除文档（放入回收站）
        /// </summary>
        /// <param name="docIds"></param>
        /// <returns></returns>
        [HttpPost]
        public string RecycleDocument(string docIds)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string entityNo = GlobalConstant.ENTITYNO;
            string[] docIdArray = docIds.Split(',');
            if (docIdArray.Length > 0)
            {
                try
                {
                    List<decimal> docIdList = new List<decimal>();
                    bool isSuccess = true;
                    foreach (string s in docIdArray)
                    {
                        decimal tmp = 0;
                        if (decimal.TryParse(s, out tmp))
                        {
                            docIdList.Add(tmp);
                        }
                        else
                        {
                            isSuccess = false;
                            break;
                        }
                    }
                    if (!isSuccess)
                    {
                        errorMessage = "信息编号参数解析错误";
                    }
                    else
                    {
                        //判断信息是否已经审核
                        isSuccess = true;
                        foreach (decimal docId in docIdList)
                        {
                            if (!documentBLL.isCanDelte(docId))
                            {
                                isSuccess = false;
                                break;
                            }
                        }
                        if (!isSuccess)
                        {
                            errorMessage = "信息中已经有审核或者已经在回收站的数据，无法删除";
                        }
                        else
                        {
                            string empNo = OperateSession.get(GlobalConstant.PARAM_FEMPLNO);
                            documentBLL.UpdateDocumentRecycle(docIdList, empNo);
                            GenerateDocStaticHtml("");
                            jsonstr = "SUCCESS";
                        }
                    }
                }
                catch (Exception ee)
                {
                    errorMessage = "操作异常:" + ee.Message;
                }
            }
            else
            {
                errorMessage = "信息编号参数错误";
            }

            if (jsonstr == "FAILED")
            {
                jsonstr += "FAILED|" + errorMessage;
            }
            return jsonstr;
        }
        /// <summary>
        /// 产生静态文件
        /// </summary>
        private void GenerateDocStaticHtml(string docClsCd)
        {
            try
            {
                if (docClsCd == "9901" || docClsCd == "9902" || docClsCd == "")
                {
                    //生成静态文件
                    string url = "http://" + Request.Url.Host + ":" + Request.Url.Port + "/ElingOA6_Accounting/Index/PageStaticHtml";

                    HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;
                    req.BeginGetResponse(null, req);
                }
            }
            catch
            {

            }

        }
        /// <summary>
        /// 生成权限权限指定部门,工作组,用户组,人
        /// </summary>
        /// <param name="ctlName">控件名称关键字</param>
        /// <param name="authorityType">权限类型</param>
        private void GenerateClsAuthorityList(string ctlName, string authorityType, string entityNo, ref List<Model.documentAuthority> documentAuthorityList)
        {
            //发布权限
            if (Fetch.Post("chk" + ctlName + "RHR") == "C")
            {
                SetClsAuthorityList("", null, authorityType, "EVERYONE", entityNo, ref documentAuthorityList);
            }
            else
            {
                if (Fetch.Post("chk" + ctlName + "QJ") == "C")
                {
                    SetClsAuthorityList("", null, authorityType, "ALL", entityNo, ref documentAuthorityList);
                }
                else
                {
                    if (authorityType != "PUB")
                    {
                        //发起部门
                        if (Fetch.Post("chk" + ctlName + "FQBM") == "C")
                        {
                            SetClsAuthorityList("cbo_" + authorityType + "_DEPT0_VI", null, authorityType, "DEPT0", entityNo, ref documentAuthorityList);
                        }
                        //发起部门上级
                        if (Fetch.Post("chk" + ctlName + "FQBM_DEPT1") == "C")
                        {
                            SetClsAuthorityList("cbo_" + authorityType + "_DEPT1_VI", null, authorityType, "DEPT1", entityNo, ref documentAuthorityList);
                        }
                        //发起部门上2级
                        if (Fetch.Post("chk" + ctlName + "FQBM_DEPT2") == "C")
                        {
                            SetClsAuthorityList("cbo_" + authorityType + "_DEPT2_VI", null, authorityType, "DEPT2", entityNo, ref documentAuthorityList);
                        }
                        //发起部门上3级
                        if (Fetch.Post("chk" + ctlName + "FQBM_DEPT3") == "C")
                        {
                            SetClsAuthorityList("cbo_" + authorityType + "_DEPT3_VI", null, authorityType, "DEPT3", entityNo, ref documentAuthorityList);
                        }
                        //发起部门上4级
                        if (Fetch.Post("chk" + ctlName + "FQBM_DEPT4") == "C")
                        {
                            SetClsAuthorityList("cbo_" + authorityType + "_DEPT4_VI", null, authorityType, "DEPT4", entityNo, ref documentAuthorityList);
                        }
                        //发起部门上5级
                        if (Fetch.Post("chk" + ctlName + "FQBM_DEPT5") == "C")
                        {
                            SetClsAuthorityList("cbo_" + authorityType + "_DEPT5_VI", null, authorityType, "DEPT5", entityNo, ref documentAuthorityList);
                        }
                        //发起部门上6级
                        if (Fetch.Post("chk" + ctlName + "FQBM_DEPT6") == "C")
                        {
                            SetClsAuthorityList("cbo_" + authorityType + "_DEPT6_VI", null, authorityType, "DEPT6", entityNo, ref documentAuthorityList);
                        }
                        //分管领导
                        if (Fetch.Post("chk" + ctlName + "Charge") == "C")
                        {
                            SetClsAuthorityList("", null, authorityType, "CHARGE", entityNo, ref documentAuthorityList);
                        }
                    }
                    string pubJson = "";
                    //部门
                    if (Fetch.Post("chk" + ctlName + "BM") == "C")
                    {
                        pubJson = Fetch.Post("hdSel" + ctlName + "DeptKeys");
                        if (pubJson != "")
                        {
                            List<CommonValueModel> pubDetpObjList = JsonConvert.DeserializeObject<List<CommonValueModel>>(pubJson);
                            SetClsAuthorityList("cbo_" + ctlName + "Dept", pubDetpObjList, authorityType, "ASSIGNDEPT", entityNo, ref documentAuthorityList);
                        }
                    }
                    if (Fetch.Post("chk" + ctlName + "GZZ") == "C")
                    {
                        //工作组
                        pubJson = Fetch.Post("hdSel" + ctlName + "WorkGroupKeys");
                        if (pubJson != "")
                        {
                            List<CommonValueModel> pubDetpObjList = JsonConvert.DeserializeObject<List<CommonValueModel>>(pubJson);
                            SetClsAuthorityList("cbo_" + ctlName + "WrokGroup", pubDetpObjList, authorityType, "GROUP", entityNo, ref documentAuthorityList);
                        }
                    }
                    if (Fetch.Post("chk" + ctlName + "GW") == "C")
                    {
                        //岗位
                        pubJson = Fetch.Post("hdSel" + ctlName + "PositionKeys");
                        if (pubJson != "")
                        {
                            List<CommonValueModel> pubDetpObjList = JsonConvert.DeserializeObject<List<CommonValueModel>>(pubJson);
                            SetClsAuthorityList("", pubDetpObjList, authorityType, "POST", entityNo, ref documentAuthorityList);
                        }
                    }
                    if (Fetch.Post("chk" + ctlName + "YHZ") == "C")
                    {
                        //用户组
                        pubJson = Fetch.Post("hdSel" + ctlName + "GroupKeys");
                        if (pubJson != "")
                        {
                            List<CommonValueModel> pubDetpObjList = JsonConvert.DeserializeObject<List<CommonValueModel>>(pubJson);
                            SetClsAuthorityList("", pubDetpObjList, authorityType, "ROLE", entityNo, ref documentAuthorityList);
                        }
                    }
                    //人员
                    if (Fetch.Post("chk" + ctlName + "User") == "C")
                    {
                        pubJson = Fetch.Post("hdSel" + ctlName + "UserKeys");
                        if (pubJson != "")
                        {
                            List<CommonValueModel> pubDetpObjList = JsonConvert.DeserializeObject<List<CommonValueModel>>(pubJson);
                            SetClsAuthorityList("", pubDetpObjList, authorityType, "PERSON", entityNo, ref documentAuthorityList);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 设置权限
        /// </summary>
        /// <param name="ctlPropName">级别性质控件名称关键字</param>
        /// <param name="commonValueList">权限数据列表</param>
        /// <param name="authorityType">权限类型</param>
        /// <param name="pronoun">代词</param>
        /// <param name="sourceNo">对应编码</param>
        /// <param name="entityNo">公司编码</param>
        /// <param name="docClsAuthorityList">权限列表，引用</param>
        private void SetClsAuthorityList(string ctlPropName, List<CommonValueModel> commonValueList, string authorityType, string pronoun, string entityNo, ref List<Model.documentAuthority> documentAuthorityList)
        {
            //发布权限
            if (commonValueList == null)
            {
                Model.documentAuthority documentAuthorityModel = new Model.documentAuthority()
                {
                    FPronoun = pronoun,
                    FProp = ctlPropName != "" ? Fetch.Post(ctlPropName) : "",
                    FSourceNo = ""
                };
                documentAuthorityList.Add(documentAuthorityModel);
            }
            else
            {
                foreach (CommonValueModel commValue in commonValueList)
                {
                    Model.documentAuthority documentAuthorityModel = new Model.documentAuthority()
                    {
                        FPronoun = pronoun,
                        FSourceNo = commValue.Value,
                        FProp = ctlPropName != "" ? Fetch.Post(ctlPropName + commValue.Value) : ""
                    };
                    documentAuthorityList.Add(documentAuthorityModel);
                }
            }
        }



        /// <summary>
        /// swfupload方法
        /// </summary>
        /// <returns></returns>
        public ActionResult Upload()
        {
            System.Drawing.Image thumbnail_image = null;//显示在信息中的图片
            System.Drawing.Image original_image = null;//原始图片
            System.Drawing.Bitmap final_image = null;//显示在页面的小图
            System.Drawing.Graphics graphic = null;
            MemoryStream ms = null;
            MemoryStream maxms = null;
            string name = "";
            int oldWidth, oldHeight, newWidth, newHeight;
            try
            {
                // Get the data
                HttpPostedFileBase jpeg_image_upload = Request.Files["Filedata"];
                name = jpeg_image_upload.FileName;

                //生成小图
                original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
                // Calculate the new width and height
                int width = original_image.Width;
                int height = original_image.Height;

                int target_width = 100;
                int target_height = 100;

                int new_width, new_height;

                oldWidth = width;
                oldHeight = height;

                float target_ratio = (float)target_width / (float)target_height;//目标比例
                float image_ratio = (float)width / (float)height;//原始比例

                if (target_ratio > image_ratio)//如果目标比例 大于 原始比例
                {
                    new_height = target_height;
                    new_width = (int)Math.Floor(image_ratio * (float)target_height);
                }
                else
                {
                    new_height = (int)Math.Floor((float)target_width / image_ratio);
                    new_width = target_width;
                }

                new_width = new_width > target_width ? target_width : new_width;
                new_height = new_height > target_height ? target_height : new_height;


                // Create the thumbnail

                // Old way
                //thumbnail_image = original_image.GetThumbnailImage(new_width, new_height, null, System.IntPtr.Zero);
                // We don't have to create a Thumbnail since the DrawImage method will resize, but the GetThumbnailImage looks better
                // I've read about a problem with GetThumbnailImage. If a jpeg has an embedded thumbnail it will use and resize it which
                //  can result in a tiny 40x40 thumbnail being stretch up to our target size


                final_image = new System.Drawing.Bitmap(target_width, target_height);//生成100*100的小图
                graphic = System.Drawing.Graphics.FromImage(final_image);
                graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height));
                int paste_x = (target_width - new_width) / 2;
                int paste_y = (target_height - new_height) / 2;
                graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
                //graphic.DrawImage(thumbnail_image, paste_x, paste_y, new_width, new_height);
                graphic.DrawImage(original_image, paste_x, paste_y, new_width, new_height);

                newWidth = new_width;
                newHeight = new_height;
                // Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
                ms = new MemoryStream();
                final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                maxms = new MemoryStream();//创建一个新的内存流
                original_image.Save(maxms, System.Drawing.Imaging.ImageFormat.Jpeg);//原始图片保存

                // Store the data in my custom Thumbnail object
                string thumbnail_id = GenerateUtil.GenerateStringId();

                Thumbnail thumb = new Thumbnail(thumbnail_id, ms.GetBuffer(), maxms.GetBuffer(), name, oldWidth, oldHeight, newWidth, newHeight);

                // Put it all in the Session (initialize the session if necessary)			
                List<Thumbnail> thumbnails = new List<Thumbnail>();
                if (PicStore.ThumbList != null)
                {
                    thumbnails = PicStore.ThumbList;
                }
                thumbnails.Add(thumb);
                PicStore.ThumbList = thumbnails;

                Response.StatusCode = 200;
                Response.Write(thumbnail_id);
            }
            catch
            {
                // If any kind of error occurs return a 500 Internal Server error
                Response.StatusCode = 500;
                Response.Write("An error occured");
                Response.End();
            }
            finally
            {
                // Clean up
                if (final_image != null) final_image.Dispose();
                if (graphic != null) graphic.Dispose();
                if (original_image != null) original_image.Dispose();
                if (thumbnail_image != null) thumbnail_image.Dispose();
                if (ms != null) ms.Close();
                Response.End();
            }
            return View();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public void Thumbnail(string id = "")
        {
            id = Request.QueryString["id"] as string;
            if (id == null)
            {
                Response.StatusCode = 404;
                Response.Write("Not Found");
                Response.End();
                return;
            }

            List<Thumbnail> thumbnails = PicStore.ThumbList;

            if (thumbnails == null)
            {
                Response.StatusCode = 404;
                Response.Write("Not Found");
                Response.End();
                return;
            }

            foreach (Thumbnail thumb in thumbnails)
            {
                if (thumb.ID == id)
                {
                    Response.ContentType = "image/jpeg";
                    Response.BinaryWrite(thumb.Data);
                    Response.End();
                    return;
                }
            }

            // If we reach here then we didn't find the file id so return 404
            Response.StatusCode = 404;
            Response.Write("Not Found");
            Response.End();
        }


        /// <summary>
        /// 删除上传图片
        /// </summary>
        /// <param name="id"></param>
        public void DelMemoryPic(string id)
        {
            if (id != "")
            {
                PicStore.ThumbList.RemoveAt(int.Parse(id) - 1);
            }
        }
        public string DelPic(string id)
        {
            string returnValue = "";
            try
            {
                string path = docAttachBLL.GetAttachSvrAddress(decimal.Parse(id));
                string pathSmall = path.Replace("s_", "ss_");
                GenerateUtil.DeleteFile(path);
                GenerateUtil.DeleteFile(pathSmall);
                docAttachBLL.DeleteDocAttach(decimal.Parse(id));

                returnValue = "ok";
            }
            catch
            {
                returnValue = "error";
            }
            return returnValue;
        }







    }
}
